import { EventBus } from '../EventBus';
import { Scene } from 'phaser';
import { webSocketManager } from '../WebSocketManager';

export class Game extends Scene
{
    constructor ()
    {
        super('Game');
        this.playerBalls = [];
        this.foods = [];
        this.spikes = [];
        this.playerScore = 10;
        this.splitCount = 0;
        this.maxSplits = 4;
        this.foodCount = 0;
        this.maxFoods = 100;
        this.spikeCount = 0;
        this.maxSpikes = 20;
        this.username = 'Player'; // 默认用户名
        
        // 多玩家相关
        this.otherPlayers = new Map(); // 存储其他玩家
        this.allPlayers = new Map();
        this.playerId = null; // 当前玩家ID
        
        // 聊天室相关
        this.chatMessages = []; // 存储聊天消息
        this.maxChatMessages = 10; // 最大显示消息数量
        this.chatInput = null; // 聊天输入框
        this.chatContainer = null; // 聊天容器
        this.chatMessagesContainer = null; // 消息显示容器
        this.isChatFocused = false; // 聊天框是否获得焦点
        
        // 排行榜相关
        this.leaderboardContainer = null; // 排行榜容器
        this.leaderboardTitle = null; // 排行榜标题
        this.leaderboardList = null; // 排行榜列表
        this.maxLeaderboardPlayers = 10; // 最多显示前10名玩家
    }

    create (data)
    {
        // 获取从主菜单传递的用户名
        if (data && data.username) {
            this.username = data.username;
        }

        // 设置背景色
        this.cameras.main.setBackgroundColor(0x87CEEB);

        // 创建世界边界
        this.physics.world.setBounds(0, 0, 2000, 2000);
        
        // 设置相机跟随
        this.cameras.main.setBounds(0, 0, 2000, 2000);
        this.cameras.main.setZoom(1);

        // 创建玩家小球 - 随机位置
        const startX = Phaser.Math.Between(100, 1900);
        const startY = Phaser.Math.Between(100, 1900);
        this.createPlayerBall(startX, startY);

        // 等待服务器发送地图数据，不在这里生成
        // this.generateFoods();
        // this.generateSpikes();

        // 设置输入
        this.setupInput();

        // 创建UI
        this.createUI();

        // 设置物理碰撞
        this.setupCollisions();

        // 移除本地定时器，等待服务器同步
        // this.time.addEvent({
        //     delay: 2000,
        //     callback: this.generateFoods,
        //     callbackScope: this,
        //     loop: true
        // });

        // 设置多玩家事件监听
        this.setupMultiplayerEvents();

        // 将游戏实例暴露到全局，方便测试
        window.gameScene = this;
        window.EventBus = EventBus;
        window.webSocketManager = webSocketManager;

        EventBus.emit('current-scene-ready', this);
    }

    createPlayerBall(x, y) {
        const ball = this.add.circle(x, y, this.playerScore, 0x00ff00);
        ball.setStrokeStyle(2, 0xffffff);
        this.physics.add.existing(ball);
        ball.body.setCollideWorldBounds(true);
        ball.body.setBounce(0.5);
        
        // 在球中心添加用户名文本
        const usernameText = this.add.text(x, y, this.username, {
            fontFamily: 'Arial', 
            fontSize: Math.max(12, this.playerScore / 3), 
            color: '#000000',
            stroke: '#ffffff',
            strokeThickness: 1,
            align: 'center'
        }).setOrigin(0.5);
        
        // 将文本附加到球上
        ball.usernameText = usernameText;
        
        this.playerBalls.push(ball);
        return ball;
    }

    generateFoods() {
        const foodsToGenerate = Math.min(10, this.maxFoods - this.foodCount);
        
        for (let i = 0; i < foodsToGenerate; i++) {
            let x, y;
            let attempts = 0;
            const maxAttempts = 50;
            
            // 尝试找到一个不与刺重合的位置
            do {
                x = Phaser.Math.Between(50, 1950);
                y = Phaser.Math.Between(50, 1950);
                attempts++;
            } while (this.isFoodPositionOccupied(x, y) && attempts < maxAttempts);
            
            // 如果找到了合适的位置，创建食物
            if (attempts < maxAttempts) {
                // 使用更鲜艳的颜色
                const colors = [0xff0000, 0x00ff00, 0x0000ff, 0xffff00, 0xff00ff, 0x00ffff, 0xff8800, 0x8800ff];
                const color = colors[Phaser.Math.Between(0, colors.length - 1)];
                
                // 创建四角星
                const food = this.createStar(x, y, color);
                this.physics.add.existing(food);
                food.body.setImmovable(true);
                food.body.setCircle(4); // 设置碰撞半径为4
                
                // 添加闪烁动画效果
                this.tweens.add({
                    targets: food,
                    alpha: 0.3,
                    duration: 500,
                    yoyo: true,
                    repeat: -1,
                    ease: 'Sine.easeInOut'
                });
                
                // 添加旋转动画
                this.tweens.add({
                    targets: food,
                    angle: 360,
                    duration: 2000,
                    repeat: -1,
                    ease: 'Linear'
                });
                
                this.foods.push(food);
                this.foodCount++;
            }
        }
    }

    isFoodPositionOccupied(x, y) {
        const minDistance = 120; // 食物半径4 + 刺半径100 + 安全距离
        
        // 检查是否与刺重合
        for (const spike of this.spikes) {
            const distance = Phaser.Math.Distance.Between(x, y, spike.x, spike.y);
            if (distance < minDistance) {
                return true;
            }
        }
        
        return false;
    }

    createStar(x, y, color) {
        // 创建四角星的路径点
        const points = [];
        const outerRadius = 4;
        const innerRadius = 2;
        
        for (let i = 0; i < 8; i++) {
            const angle = (i * Math.PI) / 4;
            const radius = i % 2 === 0 ? outerRadius : innerRadius;
            points.push({
                x: Math.cos(angle) * radius,
                y: Math.sin(angle) * radius
            });
        }
        
        // 创建星形图形
        const star = this.add.polygon(x, y, points, color);
        star.setStrokeStyle(1, 0xffffff);
        
        return star;
    }

generateSpikes() {
    const spikesToGenerate = Math.min(5, this.maxSpikes - this.spikeCount);
    
    for (let i = 0; i < spikesToGenerate; i++) {
        let x, y;
        let attempts = 0;
        const maxAttempts = 100;
        
        // 尝试找到一个不与其他刺和食物重合的位置
        do {
            x = Phaser.Math.Between(200, 1800);
            y = Phaser.Math.Between(200, 1800);
            attempts++;
        } while (this.isPositionOccupied(x, y) && attempts < maxAttempts);
        
        // 如果找到了合适的位置，创建刺
        if (attempts < maxAttempts) {
            // 创建刺（圆形），大小与玩家分数100时相同
            const spike = this.add.circle(x, y, 100, 0xff0000);
            spike.setStrokeStyle(3, 0xffffff);
            this.physics.add.existing(spike);
            spike.body.setImmovable(true);
            spike.body.setCircle(100); // 设置碰撞半径为100
            spike.body.setVelocity(0, 0); // 确保速度为0
            spike.body.setAngularVelocity(0); // 确保角速度为0
            spike.body.setGravity(0, 0); // 禁用重力
            spike.body.setDrag(0, 0); // 禁用阻力
            spike.body.setBounce(0, 0); // 禁用弹跳
            
            this.spikes.push(spike);
            this.spikeCount++;
        }
    }
}

isPositionOccupied(x, y) {
    const minDistance = 250; // 刺的半径100 + 食物半径4 + 安全距离
    
    // 检查是否与现有刺重合
    for (const spike of this.spikes) {
        const distance = Phaser.Math.Distance.Between(x, y, spike.x, spike.y);
        if (distance < minDistance) {
            return true;
        }
    }
    
    // 检查是否与食物重合
    for (const food of this.foods) {
        const distance = Phaser.Math.Distance.Between(x, y, food.x, food.y);
        if (distance < minDistance) {
            return true;
        }
    }
    
    return false;
}

    setupInput() {
        // 鼠标移动控制
        this.input.on('pointermove', (pointer) => {
            // 如果聊天框获得焦点，禁用游戏输入
            if (this.isChatFocused) {
                return;
            }
            
            if (this.playerBalls.length > 0) {
                const worldPoint = this.cameras.main.getWorldPoint(pointer.x, pointer.y);
                
                this.playerBalls.forEach(ball => {
                    const angle = Phaser.Math.Angle.Between(ball.x, ball.y, worldPoint.x, worldPoint.y);
                    const distance = Phaser.Math.Distance.Between(ball.x, ball.y, worldPoint.x, worldPoint.y);
                    
                    if (distance > 5) {
                        const speed = Math.min(200, distance * 2);
                        ball.body.setVelocity(
                            Math.cos(angle) * speed,
                            Math.sin(angle) * speed
                        );
                    }
                });
            }
        });

        // 空格键分裂
        this.input.keyboard.on('keydown-SPACE', () => {
            // 如果聊天框获得焦点，禁用游戏输入
            if (this.isChatFocused) {
                return;
            }
            this.splitPlayer();
        });
    }

    setupCollisions() {
        // 设置玩家小球和食物的碰撞检测
        this.physics.add.overlap(this.playerBalls, this.foods, this.eatFood, null, this);
        
        // 设置玩家小球和刺的碰撞检测
        this.physics.add.overlap(this.playerBalls, this.spikes, this.hitSpike, null, this);
    }

    eatFood(playerBall, food) {
        // 检查食物是否已经被销毁
        if (!food.active) {
            return;
        }
        
        // 玩家吃到食物
        this.playerScore++;
        
        // 更新所有小球的大小和用户名文本
        const newRadius = this.playerScore / this.playerBalls.length;
        this.playerBalls.forEach(b => {
            b.setRadius(newRadius);
            // 更新用户名文本的大小和位置
            if (b.usernameText) {
                b.usernameText.setFontSize(Math.max(12, newRadius / 3));
                b.usernameText.setPosition(b.x, b.y);
            }
        });
        
        // 移除食物
        const foodIndex = this.foods.indexOf(food);
        if (foodIndex > -1) {
            food.destroy();
            this.foods.splice(foodIndex, 1);
            this.foodCount--;
        }
        
        this.updateUI();
        
        // 通知服务器食物被吃掉，让服务器生成新食物
        webSocketManager.sendMessage({
            type: 'food_eaten',
            data: {
                foodId: food.foodId || Date.now(),
                timestamp: Date.now()
            }
        });
    }

    hitSpike(playerBall, spike) {
        // 检查玩家大小是否大于100
        if (this.playerScore <= 100) {
            // 玩家小于等于100，可以正常通过
            return;
        }
        
        // 检查是否完全覆盖了刺
        const distance = Phaser.Math.Distance.Between(playerBall.x, playerBall.y, spike.x, spike.y);
        const playerRadius = playerBall.radius;
        const spikeRadius = 100; // 刺的碰撞半径
        
        // 如果玩家球完全覆盖了刺（玩家半径大于距离+刺半径）
        if (playerRadius > distance + spikeRadius) {
            // 销毁被刺穿的刺
            const spikeIndex = this.spikes.indexOf(spike);
            if (spikeIndex > -1) {
                spike.destroy();
                this.spikes.splice(spikeIndex, 1);
                this.spikeCount--;
            }
            
            // 被刺穿，分裂为16个大小不等的小球
            this.splitBySpike();
        }
    }

    splitBySpike() {
        // 移除所有当前的小球
        this.playerBalls.forEach(ball => {
            if (ball.usernameText) {
                ball.usernameText.destroy();
            }
            ball.destroy();
        });
        
        // 创建16个大小不等的小球
        const newBalls = [];
        const totalScore = this.playerScore;
        
        for (let i = 0; i < 16; i++) {
            // 随机分配分数，确保总和等于原分数
            const ballScore = i === 15 ? totalScore - newBalls.reduce((sum, ball) => sum + ball.score, 0) : 
                           Math.max(1, Math.floor(totalScore / 16) + Phaser.Math.Between(-2, 2));
            
            // 基于当前玩家位置随机生成分裂球的位置
            const baseX = this.playerBalls.length > 0 ? this.playerBalls[0].x : 1000;
            const baseY = this.playerBalls.length > 0 ? this.playerBalls[0].y : 1000;
            const x = baseX + Phaser.Math.Between(-100, 100);
            const y = baseY + Phaser.Math.Between(-100, 100);
            
            const newBall = this.add.circle(x, y, ballScore, 0x00ff00);
            newBall.setStrokeStyle(2, 0xffffff);
            newBall.score = ballScore; // 存储每个球的分数
            this.physics.add.existing(newBall);
            newBall.body.setCollideWorldBounds(true);
            newBall.body.setBounce(0.5);
            
            // 在球中心添加用户名文本
            const usernameText = this.add.text(x, y, this.username, {
                fontFamily: 'Arial', 
                fontSize: Math.max(12, ballScore / 3), 
                color: '#000000',
                stroke: '#ffffff',
                strokeThickness: 1,
                align: 'center'
            }).setOrigin(0.5);
            
            // 将文本附加到球上
            newBall.usernameText = usernameText;
            
            // 给新球一个随机速度
            const angle = Phaser.Math.Between(0, Math.PI * 2);
            const speed = Phaser.Math.Between(200, 400);
            newBall.body.setVelocity(
                Math.cos(angle) * speed,
                Math.sin(angle) * speed
            );
            
            newBalls.push(newBall);
        }
        
        this.playerBalls = newBalls;
        
        // 重新设置碰撞检测
        this.setupCollisions();
        
        // 重置分裂计数
        this.splitCount = 0;
        
        this.updateUI();
    }

    splitPlayer() {
        if (this.splitCount >= this.maxSplits || this.playerBalls.length >= 16) {
            return;
        }

        const newBalls = [];
        const currentBallCount = this.playerBalls.length;
        
        this.playerBalls.forEach((ball, index) => {
            // 创建新的小球
            const newBall = this.add.circle(
                ball.x + Phaser.Math.Between(-20, 20),
                ball.y + Phaser.Math.Between(-20, 20),
                this.playerScore / (currentBallCount * 2),
                0x00ff00
            );
            newBall.setStrokeStyle(2, 0xffffff);
            this.physics.add.existing(newBall);
            newBall.body.setCollideWorldBounds(true);
            newBall.body.setBounce(0.5);
            
            // 在球中心添加用户名文本
            const usernameText = this.add.text(newBall.x, newBall.y, this.username, {
                fontFamily: 'Arial', 
                fontSize: Math.max(12, (this.playerScore / (currentBallCount * 2)) / 3), 
                color: '#000000',
                stroke: '#ffffff',
                strokeThickness: 1,
                align: 'center'
            }).setOrigin(0.5);
            
            // 将文本附加到球上
            newBall.usernameText = usernameText;
            
            // 给新球一个初始速度
            const angle = Phaser.Math.Between(0, Math.PI * 2);
            const speed = 300;
            newBall.body.setVelocity(
                Math.cos(angle) * speed,
                Math.sin(angle) * speed
            );
            
            newBalls.push(newBall);
        });

        // 移除旧球，添加新球
        this.playerBalls.forEach(ball => {
            if (ball.usernameText) {
                ball.usernameText.destroy();
            }
            ball.destroy();
        });
        this.playerBalls = newBalls;
        
        // 重新设置碰撞检测
        this.setupCollisions();
        
        this.splitCount++;
        this.updateUI();
    }

    createUI() {
        this.scoreText = this.add.text(16, 16, 'Score: ' + this.playerScore, {
            fontSize: '32px',
            fill: '#fff',
            stroke: '#000',
            strokeThickness: 4
        });
        this.scoreText.setScrollFactor(0);
        this.scoreText.setDepth(1000);

        this.splitText = this.add.text(16, 60, 'Splits: ' + this.splitCount + '/' + this.maxSplits, {
            fontSize: '24px',
            fill: '#fff',
            stroke: '#000',
            strokeThickness: 3
        });
        this.splitText.setScrollFactor(0);
        this.splitText.setDepth(1000);

        this.ballCountText = this.add.text(16, 90, 'Balls: ' + this.playerBalls.length, {
            fontSize: '24px',
            fill: '#fff',
            stroke: '#000',
            strokeThickness: 3
        });
        this.ballCountText.setScrollFactor(0);
        this.ballCountText.setDepth(1000);

        this.instructionText = this.add.text(16, 130, 'Move: Mouse | Split: Space', {
            fontSize: '18px',
            fill: '#fff',
            stroke: '#000',
            strokeThickness: 2
        });
        this.instructionText.setScrollFactor(0);
        this.instructionText.setDepth(1000);

        this.foodText = this.add.text(16, 160, 'Collect colorful stars to grow!', {
            fontSize: '16px',
            fill: '#ffff00',
            stroke: '#000',
            strokeThickness: 2
        });
        this.foodText.setScrollFactor(0);
        this.foodText.setDepth(1000);

        this.spikeText = this.add.text(16, 190, 'Avoid red circles when >100 size!', {
            fontSize: '16px',
            fill: '#ff0000',
            stroke: '#000',
            strokeThickness: 2
        });
        this.spikeText.setScrollFactor(0);
        this.spikeText.setDepth(1000);

        // 创建聊天室
        this.createChatRoom();
        
        // 创建排行榜
        this.createLeaderboard();
    }

    updateUI() {
        this.scoreText.setText('Score: ' + this.playerScore);
        this.splitText.setText('Splits: ' + this.splitCount + '/' + this.maxSplits);
        this.ballCountText.setText('Balls: ' + this.playerBalls.length);
    }

    createChatRoom() {
        // 获取游戏画布尺寸
        const gameWidth = this.cameras.main.width;
        const gameHeight = this.cameras.main.height;
        
        // 聊天室位置和尺寸
        const chatWidth = 300;
        const chatHeight = 200;
        const chatX = gameWidth - chatWidth - 20;
        const chatY = gameHeight - chatHeight - 20;
        
        // 创建聊天容器
        this.chatContainer = document.createElement('div');
        this.chatContainer.style.cssText = `
            position: absolute;
            left: ${chatX}px;
            top: ${chatY}px;
            width: ${chatWidth}px;
            height: ${chatHeight}px;
            background: rgba(0, 0, 0, 0.3);
            border: 1px solid rgba(255, 255, 255, 0.3);
            border-radius: 8px;
            backdrop-filter: blur(5px);
            z-index: 2000;
            pointer-events: auto;
            display: flex;
            flex-direction: column;
            font-family: Arial, sans-serif;
        `;
        
        // 创建聊天标题
        const chatTitle = document.createElement('div');
        chatTitle.textContent = '聊天室';
        chatTitle.style.cssText = `
            padding: 8px 12px;
            background: rgba(255, 255, 255, 0.1);
            color: white;
            font-size: 14px;
            font-weight: bold;
            border-bottom: 1px solid rgba(255, 255, 255, 0.2);
            border-radius: 8px 8px 0 0;
        `;
        
        // 创建消息显示区域
        this.chatMessagesContainer = document.createElement('div');
        this.chatMessagesContainer.style.cssText = `
            flex: 1;
            padding: 8px 12px;
            overflow-y: auto;
            color: white;
            font-size: 12px;
            line-height: 1.4;
            max-height: 120px;
        `;
        
        // 创建输入区域
        const inputContainer = document.createElement('div');
        inputContainer.style.cssText = `
            padding: 8px 12px;
            border-top: 1px solid rgba(255, 255, 255, 0.2);
            display: flex;
            gap: 8px;
        `;
        
        // 创建输入框
        this.chatInput = document.createElement('input');
        this.chatInput.type = 'text';
        this.chatInput.placeholder = '输入消息...';
        this.chatInput.style.cssText = `
            flex: 1;
            padding: 6px 8px;
            border: 1px solid rgba(255, 255, 255, 0.3);
            border-radius: 4px;
            background: rgba(255, 255, 255, 0.1);
            color: white;
            font-size: 12px;
            outline: none;
        `;
        
        // 创建发送按钮
        const sendButton = document.createElement('button');
        sendButton.textContent = '发送';
        sendButton.style.cssText = `
            padding: 6px 12px;
            border: 1px solid rgba(255, 255, 255, 0.3);
            border-radius: 4px;
            background: rgba(0, 123, 255, 0.7);
            color: white;
            font-size: 12px;
            cursor: pointer;
            outline: none;
        `;
        
        // 组装聊天室
        inputContainer.appendChild(this.chatInput);
        inputContainer.appendChild(sendButton);
        this.chatContainer.appendChild(chatTitle);
        this.chatContainer.appendChild(this.chatMessagesContainer);
        this.chatContainer.appendChild(inputContainer);
        
        // 添加到页面
        document.body.appendChild(this.chatContainer);
        
        // 添加事件监听
        this.setupChatEvents(sendButton);
        
        // 添加一些初始消息
        this.addChatMessage('系统', '欢迎来到游戏聊天室！', '#00ff00');
        this.addChatMessage('系统', '按 Enter 键快速发送消息', '#ffff00');
    }

    setupChatEvents(sendButton) {
        // 发送按钮点击事件
        sendButton.addEventListener('click', () => {
            this.sendChatMessage();
        });
        
        // 输入框回车事件
        this.chatInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                this.sendChatMessage();
            }
        });
        
        // 输入框焦点事件
        this.chatInput.addEventListener('focus', () => {
            this.isChatFocused = true;
            this.chatInput.style.background = 'rgba(255, 255, 255, 0.2)';
        });
        
        this.chatInput.addEventListener('blur', () => {
            this.isChatFocused = false;
            this.chatInput.style.background = 'rgba(255, 255, 255, 0.1)';
        });
        
        // 防止聊天室影响游戏输入
        this.chatContainer.addEventListener('mousedown', (e) => {
            e.stopPropagation();
        });
        
        this.chatContainer.addEventListener('click', (e) => {
            e.stopPropagation();
        });
    }

    sendChatMessage() {
        const message = this.chatInput.value.trim();
        if (message) {
            // 发送到服务器
            webSocketManager.sendMessage({
                type: 'chat_message',
                data: {
                    username: this.username,
                    message: message,
                    timestamp: Date.now()
                }
            });
            
            // 清空输入框
            this.chatInput.value = '';
            
            // 本地显示消息
            this.addChatMessage(this.username, message, '#ffffff');
        }
    }

    addChatMessage(username, message, color = '#ffffff') {
        const messageElement = document.createElement('div');
        messageElement.style.cssText = `
            margin-bottom: 4px;
            word-wrap: break-word;
        `;
        
        const time = new Date().toLocaleTimeString('zh-CN', { 
            hour: '2-digit', 
            minute: '2-digit' 
        });
        
        messageElement.innerHTML = `
            <span style="color: ${color}; font-weight: bold;">[${time}] ${username}:</span>
            <span style="color: white;"> ${message}</span>
        `;
        
        this.chatMessagesContainer.appendChild(messageElement);
        
        // 限制消息数量
        while (this.chatMessagesContainer.children.length > this.maxChatMessages) {
            this.chatMessagesContainer.removeChild(this.chatMessagesContainer.firstChild);
        }
        
        // 滚动到底部
        this.chatMessagesContainer.scrollTop = this.chatMessagesContainer.scrollHeight;
        
        // 存储消息
        this.chatMessages.push({
            username,
            message,
            color,
            timestamp: Date.now()
        });
    }

    createLeaderboard() {
        // 获取游戏画布尺寸
        const gameWidth = this.cameras.main.width;
        const gameHeight = this.cameras.main.height;
        
        // 排行榜位置和尺寸
        const leaderboardWidth = 250;
        const leaderboardHeight = 300;
        const leaderboardX = gameWidth - leaderboardWidth - 20;
        const leaderboardY = 20;
        
        // 创建排行榜容器
        this.leaderboardContainer = document.createElement('div');
        this.leaderboardContainer.style.cssText = `
            position: absolute;
            left: ${leaderboardX}px;
            top: ${leaderboardY}px;
            width: ${leaderboardWidth}px;
            height: ${leaderboardHeight}px;
            background: rgba(0, 0, 0, 0.4);
            border: 1px solid rgba(255, 255, 255, 0.3);
            border-radius: 8px;
            backdrop-filter: blur(5px);
            z-index: 1500;
            pointer-events: auto;
            display: flex;
            flex-direction: column;
            font-family: Arial, sans-serif;
        `;
        
        // 创建排行榜标题
        this.leaderboardTitle = document.createElement('div');
        this.leaderboardTitle.textContent = '🏆 排行榜';
        this.leaderboardTitle.style.cssText = `
            padding: 12px 16px;
            background: rgba(255, 215, 0, 0.2);
            color: #FFD700;
            font-size: 16px;
            font-weight: bold;
            text-align: center;
            border-bottom: 1px solid rgba(255, 255, 255, 0.2);
            border-radius: 8px 8px 0 0;
        `;
        
        // 创建排行榜列表
        this.leaderboardList = document.createElement('div');
        this.leaderboardList.style.cssText = `
            flex: 1;
            padding: 8px 12px;
            overflow-y: auto;
            color: white;
            font-size: 14px;
            line-height: 1.6;
        `;
        
        // 组装排行榜
        this.leaderboardContainer.appendChild(this.leaderboardTitle);
        this.leaderboardContainer.appendChild(this.leaderboardList);
        
        // 添加到页面
        document.body.appendChild(this.leaderboardContainer);
        
        // 初始化排行榜
        this.updateLeaderboard();
    }

    updateLeaderboard() {
        if (!this.leaderboardList) return;
        
        // 获取所有玩家（包括当前玩家和其他玩家）
        const allPlayers = new Map();
        
        // 添加当前玩家
        if (this.playerBalls.length > 0) {
            allPlayers.set(this.playerId, {
                playerId: this.playerId,
                username: this.username,
                score: this.playerScore,
                isCurrentPlayer: true
            });
        }
        
        // 添加其他玩家
        this.otherPlayers.forEach((ball, playerId) => {
            allPlayers.set(playerId, {
                playerId: playerId,
                username: ball.username || `Player${playerId}`,
                score: ball.radius || 10,
                isCurrentPlayer: false
            });
        });
        
        // 按分数倒序排列
        const sortedPlayers = Array.from(allPlayers.values())
            .sort((a, b) => b.score - a.score)
            .slice(0, this.maxLeaderboardPlayers);
        
        // 清空排行榜列表
        this.leaderboardList.innerHTML = '';
        
        // 添加玩家条目
        sortedPlayers.forEach((player, index) => {
            const playerElement = document.createElement('div');
            playerElement.style.cssText = `
                display: flex;
                justify-content: space-between;
                align-items: center;
                padding: 6px 8px;
                margin-bottom: 4px;
                border-radius: 4px;
                background: ${player.isCurrentPlayer ? 'rgba(0, 123, 255, 0.3)' : 'rgba(255, 255, 255, 0.1)'};
                border: 1px solid ${player.isCurrentPlayer ? 'rgba(0, 123, 255, 0.5)' : 'rgba(255, 255, 255, 0.2)'};
            `;
            
            const rank = index + 1;
            const rankIcon = rank === 1 ? '🥇' : rank === 2 ? '🥈' : rank === 3 ? '🥉' : `${rank}.`;
            
            playerElement.innerHTML = `
                <div style="display: flex; align-items: center; gap: 8px;">
                    <span style="font-weight: bold; color: ${rank <= 3 ? '#FFD700' : '#ffffff'}; min-width: 30px;">
                        ${rankIcon}
                    </span>
                    <span style="color: ${player.isCurrentPlayer ? '#00ffff' : '#ffffff'}; font-weight: ${player.isCurrentPlayer ? 'bold' : 'normal'};">
                        ${player.username}
                    </span>
                </div>
                <span style="color: #00ff00; font-weight: bold;">
                    ${player.score}
                </span>
            `;
            
            this.leaderboardList.appendChild(playerElement);
        });
        
        // 如果没有玩家，显示提示信息
        if (sortedPlayers.length === 0) {
            const noPlayersElement = document.createElement('div');
            noPlayersElement.style.cssText = `
                text-align: center;
                color: rgba(255, 255, 255, 0.7);
                padding: 20px;
                font-style: italic;
            `;
            noPlayersElement.textContent = '暂无玩家数据';
            this.leaderboardList.appendChild(noPlayersElement);
        }
    }

    update() {
        // 备用碰撞检测 - 只检测食物碰撞，刺的碰撞由Phaser物理引擎处理
        const foodsToRemove = [];
        
        this.playerBalls.forEach(ball => {
            // 检测食物碰撞
            this.foods.forEach(food => {
                if (food.active) {
                    const distance = Phaser.Math.Distance.Between(ball.x, ball.y, food.x, food.y);
                    const collisionDistance = ball.radius + 4; // 食物的碰撞半径是4
                    
                    if (distance <= collisionDistance) {
                        if (!foodsToRemove.includes(food)) {
                            foodsToRemove.push(food);
                        }
                    }
                }
            });
        });

        // 处理被检测到的食物
        foodsToRemove.forEach(food => {
            this.eatFood(null, food);
        });

        // 检测玩家之间的碰撞（吃玩家功能）
        this.checkPlayerCollisions();

        // 确保所有刺都保持静止
        this.spikes.forEach(spike => {
            if (spike.active && spike.body) {
                spike.body.setVelocity(0, 0);
                spike.body.setAngularVelocity(0);
            }
        });

        // 更新相机位置（跟随第一个小球）和用户名文本位置
        if (this.playerBalls.length > 0) {
            const firstBall = this.playerBalls[0];
            this.cameras.main.centerOn(firstBall.x, firstBall.y);
            
            // 更新所有小球的用户名文本位置
            this.playerBalls.forEach(ball => {
                if (ball.usernameText) {
                    ball.usernameText.setPosition(ball.x, ball.y);
                }
            });
        }

        // 更新其他玩家的用户名文本位置
        this.otherPlayers.forEach((ball, playerId) => {
            if (ball.usernameText) {
                ball.usernameText.setPosition(ball.x, ball.y);
            }
        });

        // 定期发送玩家状态更新到服务器（每500毫秒发送一次，提高同步频率）
        if (!this.lastStatusUpdate || this.time.now - this.lastStatusUpdate > 500) {
            this.sendPlayerStatus();
            this.lastStatusUpdate = this.time.now;
        }
        
        // 更新排行榜
        this.updateLeaderboard();
    }

    checkPlayerCollisions() {
        // 检查当前玩家与其他玩家的碰撞
        this.playerBalls.forEach(playerBall => {
            this.otherPlayers.forEach((otherBall, otherPlayerId) => {
                if (!otherBall.active) return;
                
                const distance = Phaser.Math.Distance.Between(playerBall.x, playerBall.y, otherBall.x, otherBall.y);
                const playerRadius = playerBall.radius;
                const otherRadius = otherBall.radius;
                
                // 检查是否完全覆盖（大玩家吃小玩家）
                if (distance + otherRadius <= playerRadius) {
                    // 当前玩家更大，吃掉其他玩家
                    this.eatOtherPlayer(otherPlayerId, otherBall);
                } else if (distance + playerRadius <= otherRadius) {
                    // 其他玩家更大，当前玩家被吃掉
                    this.getEatenByOtherPlayer(otherPlayerId, otherBall);
                }
            });
        });
    }

    eatOtherPlayer(otherPlayerId, otherBall) {
        console.log(`玩家 ${this.username} 吃掉了玩家 ${otherBall.username}`);
        
        // 增加当前玩家的分数
        const eatenScore = otherBall.radius;
        this.playerScore += eatenScore;
        
        // 更新所有小球的大小和用户名文本
        const newRadius = this.playerScore / this.playerBalls.length;
        this.playerBalls.forEach(b => {
            b.setRadius(newRadius);
            if (b.usernameText) {
                b.usernameText.setFontSize(Math.max(12, newRadius / 3));
                b.usernameText.setPosition(b.x, b.y);
            }
        });
        
        // 销毁被吃掉的玩家
        if (otherBall.usernameText) {
            otherBall.usernameText.destroy();
        }
        otherBall.destroy();
        this.otherPlayers.delete(otherPlayerId);
        
        // 更新UI
        this.updateUI();
        
        // 发送吃玩家事件到服务器
        webSocketManager.sendMessage({
            type: 'player_eaten',
            data: {
                eaterId: this.playerId,
                eatenId: otherPlayerId,
                eatenScore: eatenScore,
                eaterUsername: this.username,
                eatenUsername: otherBall.username
            }
        });
        
        // 在聊天室显示吃玩家消息
        this.addChatMessage('系统', `${this.username} 吃掉了 ${otherBall.username}！`, '#ff0000');
    }

    getEatenByOtherPlayer(otherPlayerId, otherBall) {
        console.log(`玩家 ${this.username} 被玩家 ${otherBall.username} 吃掉了`);
        
        // 在聊天室显示被吃消息
        this.addChatMessage('系统', `${this.username} 被 ${otherBall.username} 吃掉了！`, '#ff0000');
        
        // 发送被吃事件到服务器
        webSocketManager.sendMessage({
            type: 'player_eaten',
            data: {
                eaterId: otherPlayerId,
                eatenId: this.playerId,
                eatenScore: this.playerScore,
                eaterUsername: otherBall.username,
                eatenUsername: this.username
            }
        });
        
        // 游戏结束，切换到游戏结束场景
        this.scene.start('GameOver', {
            finalScore: this.playerScore,
            reason: `被 ${otherBall.username} 吃掉`,
            winner: otherBall.username
        });
    }

    sendPlayerStatus() {
        if (this.playerBalls.length > 0) {
            const mainBall = this.playerBalls[0];
            const status = {
                position: {
                    x: Math.round(mainBall.x),
                    y: Math.round(mainBall.y)
                },
                score: this.playerScore,
                ballCount: this.playerBalls.length,
                splitCount: this.splitCount,
                username: this.username,
                playerId: this.playerId
            };
            webSocketManager.sendPlayerStatus(this.username, status);
        }
    }

    setupMultiplayerEvents() {
        // 监听其他玩家更新
        EventBus.on('player_update', this.handlePlayerUpdate, this);
        EventBus.on('player_join', this.handlePlayerJoin, this);
        EventBus.on('player_leave', this.handlePlayerLeave, this);
        EventBus.on('player_id_assigned', this.handlePlayerIdAssigned, this);
        
        // 监听地图同步
        EventBus.on('map_data', this.handleMapData, this);
        EventBus.on('food_spawn', this.handleFoodSpawn, this);
        EventBus.on('spike_spawn', this.handleSpikeSpawn, this);
        // 监听聊天消息
        EventBus.on('chat_message', this.handleChatMessage, this);
        // 监听玩家被吃掉事件
        EventBus.on('player_eaten', this.handlePlayerEaten, this);
    }

    handlePlayerIdAssigned(playerId) {
        this.playerId = playerId;
        console.log('玩家ID已分配:', playerId);
    }

    handlePlayerUpdate(data) {
        const { playerId, position, score, username, ballCount } = data;
        
        console.log('收到玩家更新:', { playerId, position, score, username, myPlayerId: this.playerId });
        
        if (playerId === this.playerId) {
            console.log('忽略自己的更新');
            return; // 忽略自己的更新
        }
        
        if (!this.otherPlayers.has(playerId)) {
            // 创建新的其他玩家球
            const otherPlayerBall = this.createOtherPlayerBall(position.x, position.y, username, score);
            this.otherPlayers.set(playerId, otherPlayerBall);
            console.log('新玩家加入:', username, '位置:', position, '当前其他玩家数量:', this.otherPlayers.size);
        } else {
            // 更新现有玩家位置和状态
            const ball = this.otherPlayers.get(playerId);
            ball.setPosition(position.x, position.y);
            ball.setRadius(score);
            
            // 更新用户名文本
            if (ball.usernameText) {
                ball.usernameText.setPosition(position.x, position.y);
                ball.usernameText.setFontSize(Math.max(12, score / 3));
            }
            
            // 保存用户名信息用于排行榜
            ball.username = username;
            
            console.log('更新玩家位置:', username, '新位置:', position);
        }
    }

    handlePlayerJoin(data) {
        const { playerId, username, position } = data;
        
        console.log('收到玩家加入:', { playerId, username, position, myPlayerId: this.playerId });
        
        if (playerId === this.playerId) {
            console.log('忽略自己的加入');
            return; // 忽略自己的加入
        }
        
        console.log('玩家加入游戏:', username, '位置:', position);
        
        // 创建其他玩家球
        const otherPlayerBall = this.createOtherPlayerBall(position.x, position.y, username, 10);
        otherPlayerBall.username = username; // 保存用户名信息用于排行榜
        this.otherPlayers.set(playerId, otherPlayerBall);
        console.log('创建其他玩家球完成，当前其他玩家数量:', this.otherPlayers.size);
    }

    handlePlayerLeave(data) {
        const { playerId } = data;
        
        if (this.otherPlayers.has(playerId)) {
            const ball = this.otherPlayers.get(playerId);
            
            // 销毁玩家球和用户名文本
            if (ball.usernameText) {
                ball.usernameText.destroy();
            }
            ball.destroy();
            
            this.otherPlayers.delete(playerId);
            console.log('玩家离开游戏:', playerId);
        }
    }

    handleMapData(data) {
        const { foods, spikes } = data;
        console.log('收到地图数据:', { foodsCount: foods.length, spikesCount: spikes.length });
        
        // 清理现有地图
        this.foods.forEach(food => food.destroy());
        this.spikes.forEach(spike => spike.destroy());
        this.foods = [];
        this.spikes = [];
        
        // 创建同步的食物
        foods.forEach(foodData => {
            const food = this.createStar(foodData.x, foodData.y, foodData.color);
            this.foods.push(food);
        });
        
        // 创建同步的刺
        spikes.forEach(spikeData => {
            const spike = this.add.circle(spikeData.x, spikeData.y, 8, 0x000000);
            spike.setStrokeStyle(2, 0xffffff);
            this.physics.add.existing(spike);
            spike.body.setImmovable(true);
            this.spikes.push(spike);
        });
        
        console.log('地图同步完成');
    }

    handleFoodSpawn(data) {
        console.log('收到食物生成:', data);
        // debugger;
        const { x, y, color } = data;
        const food = this.createStar(x, y, color);
        this.foods.push(food);
        console.log('食物生成:', { x, y, color });
    }

    handleSpikeSpawn(data) {
        const { x, y } = data;
        const spike = this.add.circle(x, y, 8, 0x000000);
        spike.setStrokeStyle(2, 0xffffff);
        this.physics.add.existing(spike);
        spike.body.setImmovable(true);
        this.spikes.push(spike);
        console.log('刺生成:', { x, y });
    }

    handleChatMessage(data) {
        const { username, message, timestamp } = data;
        
        // 忽略自己的消息（已经在发送时显示过了）
        if (username === this.username) {
            return;
        }
        
        // 显示其他玩家的消息
        this.addChatMessage(username, message, '#00ffff');
        console.log('收到聊天消息:', { username, message, timestamp });
    }

    handlePlayerEaten(data) {
        const { eaterId, eatenId, eatenScore, eaterUsername, eatenUsername } = data;
        console.log('收到玩家被吃掉事件:', { eaterId, eatenId, eatenScore, eaterUsername, eatenUsername });
        
        // 如果被吃掉的是当前玩家，且不是自己触发的（避免重复处理）
        if (eatenId === this.playerId && eaterId !== this.playerId) {
            console.log('当前玩家被其他玩家吃掉');
            // 游戏结束，切换到游戏结束场景
            this.scene.start('GameOver', {
                finalScore: this.playerScore,
                reason: `被 ${eaterUsername} 吃掉`,
                winner: eaterUsername
            });
        }
        
        // 如果被吃掉的是其他玩家，且不是自己触发的
        if (eatenId !== this.playerId && eaterId !== this.playerId) {
            // 从otherPlayers中移除被吃掉的玩家
            if (this.otherPlayers.has(eatenId)) {
                const ball = this.otherPlayers.get(eatenId);
                if (ball.usernameText) {
                    ball.usernameText.destroy();
                }
                ball.destroy();
                this.otherPlayers.delete(eatenId);
                console.log('移除被吃掉的玩家:', eatenUsername);
            }
        }
    }

    createOtherPlayerBall(x, y, username, score) {
        // 创建其他玩家的球（红色）
        const ball = this.add.circle(x, y, score, 0xff0000);
        ball.setStrokeStyle(2, 0xffffff);
        this.physics.add.existing(ball);
        ball.body.setCollideWorldBounds(true);
        ball.body.setBounce(0.5);
        
        // 在球中心添加用户名文本
        const usernameText = this.add.text(x, y, username, {
            fontFamily: 'Arial', 
            fontSize: Math.max(12, score / 3), 
            color: '#ffffff',
            stroke: '#000000',
            strokeThickness: 1,
            align: 'center'
        }).setOrigin(0.5);
        
        // 将文本附加到球上
        ball.usernameText = usernameText;
        
        return ball;
    }

    changeScene ()
    {
        // 清理多玩家事件监听
        EventBus.off('player_update', this.handlePlayerUpdate, this);
        EventBus.off('player_join', this.handlePlayerJoin, this);
        EventBus.off('player_leave', this.handlePlayerLeave, this);
        EventBus.off('player_id_assigned', this.handlePlayerIdAssigned, this);
        EventBus.off('map_data', this.handleMapData, this);
        EventBus.off('food_spawn', this.handleFoodSpawn, this);
        EventBus.off('spike_spawn', this.handleSpikeSpawn, this);
        EventBus.off('chat_message', this.handleChatMessage, this);
        EventBus.off('player_eaten', this.handlePlayerEaten, this);
        
        // 清理其他玩家
        this.otherPlayers.forEach((ball, playerId) => {
            if (ball.usernameText) {
                ball.usernameText.destroy();
            }
            ball.destroy();
        });
        this.otherPlayers.clear();
        
        // 清理聊天室
        if (this.chatContainer) {
            document.body.removeChild(this.chatContainer);
            this.chatContainer = null;
            this.chatInput = null;
            this.chatMessagesContainer = null;
        }
        
        // 清理排行榜
        if (this.leaderboardContainer) {
            document.body.removeChild(this.leaderboardContainer);
            this.leaderboardContainer = null;
            this.leaderboardTitle = null;
            this.leaderboardList = null;
        }
        
        // 发送游戏结束消息
        webSocketManager.sendMessage({
            type: 'game_end',
            data: {
                finalScore: this.playerScore,
                timestamp: Date.now()
            }
        });
        
        this.scene.start('GameOver');
    }
}
